from django.shortcuts import render
from django.views import View
from libs.captcha.captcha import captcha
from django_redis import get_redis_connection
from django.http import HttpResponse, JsonResponse
import json, re
from random import randint
from celery_tasks.sms.tasks import celery_send_sms_code
from utils.response_code import RET


# Create your views here.

class ImageCodeView(View):
    """获取图片验证码"""

    def get(self, request):
        # 获取参数
        cur_uuid = request.GET.get('cur')
        pre_uuid = request.GET.get('pre')

        # 验证参数
        # 生成文本和图片的二进制
        text, image = captcha.generate_captcha()
        # 文本保存在redis
        redis_cli = get_redis_connection('code')
        redis_cli.delete(f'image_{pre_uuid}')
        redis_cli.setex(f'image_{cur_uuid}', 100, text)
        # 返回图片的二进制
        return HttpResponse(image, content_type='image/jpeg')


class SMSCodeView(View):
    """获取短信验证码"""

    def post(self, request):
        # 获取参数
        data = json.loads(request.body.decode())
        mobile = data.get('mobile')
        id = data.get('id')
        text = data.get('text')
        # 验证参数

        # 验证手机号码格式
        if not re.match(r'^1[3-9]\d{9}$', mobile):
            return JsonResponse({'errno': RET.PARAMERR, 'errmsg': 'mobile格式错误'})

        # 链接redis
        redis_cli = get_redis_connection('code')
        image_code = redis_cli.get(f'image_{id}')
        if text.upper() != image_code.decode().upper():
            return JsonResponse({'errno': RET.PARAMERR, 'errmsg': '图片验证码错误'})

        send_flag = redis_cli.get(f'send_flag_{mobile}')
        if send_flag:
            return JsonResponse({'code': RET.REQERR, 'errmsg': '发送短信频繁'})

        # 生成短信验证码
        sms_code = randint(100000, 999999)
        print(f'{sms_code}')

        # 管道三步
        # 一. 创建管道
        pipeline = redis_cli.pipeline()
        # 二. 搜集指令
        pipeline.setex(mobile, 300, sms_code)
        # 设置发送标记
        pipeline.setex(f'send_flag_{mobile}', 60, 1)
        # 三. 执行指令
        pipeline.execute()

        celery_send_sms_code.delay(mobile, sms_code)
        return JsonResponse({'errno': RET.OK, 'errmsg': 'ok'})
